<template>
	<el-card class="layout-query">
		<el-form :inline="true" label-width="100px">
			<el-form-item label="关键词" prop="keyword">
				<el-input v-model="state.keyword" placeholder="请输入">
					<template #prepend>
						<el-select v-model="state.keyType" placeholder="请选择" style="width: 100px; min-width: 100px" @change="handleSelectChange">
							<el-option label="项目名称" value="1" />
							<el-option label="项目编号" value="2" />
							<el-option label="负责人" value="3" />
							<el-option label="联系人" value="4" />
							<!-- <el-option label="承担单位" value="5" /> -->
						</el-select>
					</template>
				</el-input>
			</el-form-item>

			<el-form-item prop="job_status" label="申报年份">
				<el-date-picker
					v-model="datatimelist"
					type="yearrange"
					range-separator="至"
					start-placeholder="开始日期"
					value-format="YYYY"
					end-placeholder="结束日期"
					@change="handleDateChange"
				/>
			</el-form-item>

			<el-form-item prop="dept_id" label="申报阶段">
				<el-select v-model="state.queryForm.processStage" placeholder="请选择" style="width: 100%">
					<el-option v-for="item in progressStatelist" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item prop="job_status" label="申报状态">
				<el-select v-model="state.queryForm.processStatus" placeholder="请选择" style="width: 100%">
					<el-option v-for="item in processStatuslist" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item prop="zy" label="申报结果">
				<el-select v-model="state.queryForm.approvalReview" placeholder="请选择" style="width: 100%">
					<el-option v-for="item in approvalReviewlist" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item>
				<el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button @click="reset">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>

	<el-card>
		<el-form :inline="true" style="text-align: right">
			<el-form-item>
				<el-button v-auth="'M005_Download'" type="primary" @click="downloadHandle">项目建议书下载</el-button>
			</el-form-item>

			<el-form-item>
				<el-button v-auth="'M005_A'" type="primary" @click="hadleAdd">新增</el-button>
			</el-form-item>
		</el-form>

		<!-- v-auth="'M005_Add'"  icon="Plus"-->
		<el-table
			v-loading="loading"
			:data="dataList"
			stripe
			border
			element-loading-background="rgba(0, 0, 0, 0.5)"
			element-loading-text="加载中..."
			header-row-class-name="table-header"
		>
			<!-- <el-table-column type="selection" header-align="center" align="center" width="55" fixed="left" /> -->
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60" fixed="left"></el-table-column>
			<el-table-column label="项目名称" align="center" prop="researchName" width="200" show-overflow-tooltip fixed="left" resizable sortable />
			<el-table-column label="联系人" align="center" prop="contacts" width="150" resizable sortable> </el-table-column>
			<el-table-column label="联系电话" align="center" prop="contactsTel" width="150" resizable sortable> </el-table-column>
			<el-table-column label="负责人" align="center" prop="principal" width="150" resizable sortable> </el-table-column>
			<el-table-column label="负责人电话(手机)" align="center" prop="principalTel" width="150" resizable sortable> </el-table-column>
			<el-table-column label="承担单位" align="center" prop="responsibleEnt" width="200" show-overflow-tooltip resizable sortable> </el-table-column>
			<el-table-column label="课题总经费(万元)" align="center" prop="projectFunding" width="150" resizable sortable> </el-table-column>
			<el-table-column label="申报年份" align="center" prop="applyYear" resizable sortable> </el-table-column>
			<el-table-column label="项目管理员" align="center" prop="projectManager" width="160" resizable sortable> </el-table-column>
			<el-table-column label="申报阶段" align="center" width="120" resizable sortable>
				<template #default="scope">
					{{ getProgressStateName(scope.row.processStage) }}
				</template>
			</el-table-column>
			<el-table-column label="申报状态" align="center" width="120" resizable sortable>
				<template #default="scope">
					<div v-if="Number(scope.row.processStatus) === 6 || Number(scope.row.processStatus) === 8" class="flex flex-align-center">
						<div>{{ getprocessStatusName(scope.row.processStatus) }}</div>
						<el-popover placement="top-start" :width="200" trigger="hover" :content="scope.row.returnOpinion">
							<template #reference>
								<el-icon color="#fe6360" style="margin-left: 5px" class="cursor"><Warning /></el-icon>
							</template>
						</el-popover>
					</div>
					<div v-else>{{ getprocessStatusName(scope.row.processStatus) }}</div>
				</template>
			</el-table-column>
			<el-table-column label="申报结果" align="center" width="120" resizable sortable>
				<template #default="scope">
					{{ scope.row.approvalReview ? (scope.row.approvalReview === '6' ? '立项' : '不立项') : '' }}
				</template>
			</el-table-column>

			<!-- <el-table-column label="退回意见" align="center" prop="returnOpinion" width="250" show-overflow-tooltip>
				<template #default="scope">
					<el-tooltip
						v-if="Number(scope.row.processStatus) === 6 || Number(scope.row.processStatus) === 8"
						:content="scope.row.returnOpinion"
						placement="top"
						effect="light"
					>
						<div class="truncate-text">{{ scope.row.returnOpinion }}</div>
					</el-tooltip>
				</template>
			</el-table-column> -->

			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="120">
				<template #default="scope">
					<el-icon
						v-if="
							scope.row.processStatus === '0' || scope.row.processStatus === '3' || scope.row.processStatus === '8' || scope.row.processStatus === '6'
						"
						v-auth="'M005_U'"
						:size="16"
						color="#1491FF"
						title="编辑"
						style="cursor: pointer; margin: 0 6px"
						@click="viewHandle(scope.row, true)"
					>
						<Edit />
					</el-icon>
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="viewHandle(scope.row, false)">
						<View />
					</el-icon>
					<el-icon
						v-if="scope.row.processStatus === '0'"
						v-auth="'M005_D'"
						:size="16"
						color="#fe6360"
						title="删除"
						style="cursor: pointer; margin: 0 6px"
						@click="deleteBatchHandle(scope.row.id)"
					>
						<Delete />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
	</el-card>
	<add v-model:visible="addvisible" :isedit="isedit1" :sid="state.id" @success="reset" />
</template>
<script setup lang="ts">
import { deleteApi, queryApplyListApi } from '@/api/Prospect-project/project-declare'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import { nextTick, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import add from './components/add.vue'
import { querylistApi } from '@/api/system/deadlineTime'

const router = useRouter()
const queryParams = ref({ keywords: '', dept_id: '', job_status: '', min: '', max: '', startTime: '', endTime: '', zy: '' })

const route = useRoute()
const pendingStatus = route.query.pendingStatus

const state = reactive({
	queryForm: {
		researchName: '',
		projectNumber: '',
		principal: '',
		contacts: '',
		processStage: '',
		processStatus: '',
		approvalReview: '',
		startYear: '',
		endYear: '',
		pendingStatus: pendingStatus || ''
	},
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false,
	keyType: '',
	keyword: null,
	yearrange: [],
	id: null
})
const queryForm = ref()
const datatimelist = ref([])
const loading = ref(false)
const dictionaryStore = useDictionaryStore()
const progressStatelist = dictionaryStore.getDictionaryByCode('T011')
const processStatuslist = dictionaryStore.getDictionaryByCode('T0029')
const approvalReviewlist = dictionaryStore.getDictionaryByCode('T013')
const userStore = useUserStore()
const addvisible = ref(false)
const dataList = ref([])
onMounted(() => {
	getDataList()
})

const downloadHandle = () => {
	try {
		const data = {
			// ids: ids,
			fileName: '科研项目建议书'
		}
		axios({
			method: 'post',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/scientificResearchInfo/downloadByFileName',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			data: data,
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = '科研项目建议书.doc'
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}
const handleDateChange = val => {
	// 清空时，val 为 null，手动设置为空字符串

	datatimelist.value = val || [] // 清空时重置为空数组
	state.queryForm.startYear = datatimelist.value[0] || ''
	state.queryForm.endYear = datatimelist.value[1] || ''
}

const queryParams1 = ref({ settingYear: '', activeStatus: '', stageCode: 'ScientificResearchApply', remark: '', preparationType: '' })
const pageInfo1 = ref({ pageIndex: 1, pageSize: 10000, total: 0 })
const isedit1 = ref(false)
const hadleAdd = () => {
	queryParams1.value.settingYear = moment().format('YYYY')
	const data = { ...queryParams1.value, pageIndex: pageInfo1.value.pageIndex, pageSize: pageInfo1.value.pageSize }
	let list = []
	querylistApi(data)
		.then(res => {
			list = res.data.list
			nextTick(() => {
				if (list.length > 0) {
					const hasZero = list.filter(item => item.activeStatus === 0)
					if (hasZero.length > 0) {
						const time = moment().format('YYYY-MM-DD')
						if (time > hasZero[0].deadLineTime) {
							ElMessageBox.confirm('申报截止时间已过，无法申报', '提示', {
								type: 'warning'
							})
								.then(() => {})
								.catch(() => {})
						} else {
							state.id = ''
							addvisible.value = true
							isedit1.value = true
						}
					} else {
						state.id = ''
						addvisible.value = true
						isedit1.value = true
					}
				} else {
					state.id = ''
					addvisible.value = true
					isedit1.value = true
				}
			})
		})
		.catch(err => {
			state.id = ''
			addvisible.value = true
			isedit1.value = true
		})
}

const handleSelectChange = () => {
	state.keyword = ''
	state.queryForm.projectNumber = ''
	state.queryForm.researchName = ''
	state.queryForm.principal = ''
	state.queryForm.contacts = ''
}
const viewHandle = (row, aa) => {
	const data = moment().format('YYYY-MM-DD HH:mm:ss')
	// if (row.applyDeadline < data) {
	// 	ElMessageBox.confirm('该申报项目已截止，请重新选择申报项目', '提示', {
	// 		type: 'warning'
	// 	})
	// 		.then(() => {})
	// 		.catch(() => {})
	// } else {
		const { id } = row
		state.id = id

		addvisible.value = true
		isedit1.value = aa
	// }
}
const getProgressStateName = (row: any) => {
	switch (row) {
		case '0':
			return '申报中'
		case '1':
			return '预审'
		case '2':
			return '立项评审(最终结论) '
		case '3':
			return '开题'
		case '4':
			return '中期'
		case '5':
			return '结题'
		case '6':
			return '等待归档'
		case '7':
			return '归档'
	}
}

const getprocessStatusName = (row: any) => {
	switch (row) {
		case '0':
			return '未提交'
		case '1':
			return '未处理'
		case '2':
			return '已处理'
		case '3':
			return '归档'
		case '5':
			return '未立项'
		case '6':
			return '申请退回'
		case '8':
			return '归档退回'
	}
}

const handleSearch = () => {
	getDataList()
}
const getDataList = () => {
	switch (state.keyType) {
		case '1':
			state.queryForm.researchName = state.keyword
			break
		case '2':
			state.queryForm.projectNumber = state.keyword
			break
		case '3':
			state.queryForm.principal = state.keyword
			break
		case '4':
			state.queryForm.contacts = state.keyword
			break
	}

	state.dataListLoading = true
	queryApplyListApi({
		pageIndex: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		state.dataListLoading = false
		dataList.value = res.data.list || []
		state.total = res.data.total || 0
	})
}
const search = () => {
	state.pageNum = 1
	getDataList()
}

// const godetail = () => {
// 	router.push({
// 		path: '/bzjddetail'
// 	})
// }

const reset = () => {
	state.queryForm.startYear = ''
	state.queryForm.endYear = ''
	state.queryForm.researchName = ''
	state.queryForm.projectNumber = ''
	state.queryForm.principal = ''
	state.queryForm.contacts = ''
	state.queryForm.processStage = ''
	state.queryForm.processStatus = ''
	state.queryForm.approvalReview = ''
	state.queryForm.pendingStatus = ''

	state.keyword = null
	state.keyType = ''
	state.pageNum = 1
	datatimelist.value = []
	getDataList()
}

const sizeChangeHandle = (e: number) => {
	state.pageSize = e
	state.pageNum = 1
	getDataList()
}
const currentChangeHandle = (e: number) => {
	state.pageNum = e
	getDataList()
}

// const getUserList = () => {
// 	queryUserApi({
// 		cnName: '',
// 		loginName: '',
// 		pageIndex: 1,
// 		pageSize: 1000
// 	}).then(res => {
// 		userDatalist.value = res.data.list
// 	})
// }

const deleteBatchHandle = (id: String | Number) => {
	ElMessageBox.confirm('是否删除?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			delMethods(id)
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败'
			})
		})
}

const delMethods = async (id: String | Number) => {
	await deleteApi({ id: id }).then(res => {
		ElMessage.success('删除成功')
		reset()
	})
}
</script>

<style lang="scss" scoped>
.el-form--inline .el-form-item {
	margin-right: 10px !important;
}
</style>
